import axios from 'axios'
import {Message} from 'element-ui'
import {showFullScreenLoading, tryHideFullScreenLoading} from "../common/globalLoading";
import router from "../router";
import api from '../api/apiPath'
const obj2Param = (object) => {
    let params = [];
    for (const key in object) {
        if (object.hasOwnProperty(key)) {
            const element = object[key];
            params.push(key + '=' + object[key])
        }
    }
    return params.join('&')
}

// 本地环境改前面路径， 打包改后面路径
const baseURL = api.domain
// create an axios instance
const service = axios.create({
    baseURL: baseURL, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    //timeout: 30000 // request timeout
})

// request interceptor
axios.interceptors.request.use((config) => {
    showFullScreenLoading()
    config.headers = {
        'Content-Type': 'application/json',
        "token": localStorage.getItem("cmsUser") ? JSON.parse(localStorage.getItem("cmsUser")).tokenId : '',
        'AJAX': 'ajax'
    }
    return config
}, (error) => {
    return Promise.reject(error)
})

// response interceptor
axios.interceptors.response.use((response) => {
    tryHideFullScreenLoading()
    if (response.data.code === 402 || response.data.code === 100) {
        router.push({path: '/login'})
    }
    if (response.data.code === 200) {
        return Promise.resolve(response)
    } else {
        if (response.data.msg) {
            Message({
                message: response.data.msg || 'Error',
                type: 'error',
                duration: 3 * 1000
            })
        }
        return Promise.reject(response)
    }
}, (error) => {
    tryHideFullScreenLoading()
    return Promise.reject(error)
})

// request interceptor
service.interceptors.request.use((config) => {
    showFullScreenLoading()
    config.headers = {
        'Content-Type': 'application/json',
        "token": localStorage.getItem("cmsUser") ? JSON.parse(localStorage.getItem("cmsUser")).tokenId : '',
        'AJAX': 'ajax'
    };
    return config
}, (error) => {
    return Promise.reject(error)
});

// response interceptor
service.interceptors.response.use((response) => {
    tryHideFullScreenLoading()
    if (response.data.code === 402 || response.data.code === 100) {
        router.push({path: '/login'})
    }
    if (response.data.code === 200) {
        return Promise.resolve(response)
    } else {
        if (response.data.msg) {
            Message({
                message: response.data.msg || 'Error',
                type: 'error',
                duration: 3 * 1000
            })
        }
        return Promise.reject(response)
    }
}, (error) => {
    tryHideFullScreenLoading()
    return Promise.reject(error)
})

const get = (url, data = {}) => {
    const objParams = obj2Param(data);
    let params = ''
    if (objParams.length) {
        params = '?' + objParams
    }
    return new Promise((resolve, reject)=>{
        return service({
            url: url + params,
            method: 'GET',
            data
        }) .then((res)=>{
            resolve(res.data.data)
        }).catch((err)=>{
            reject(err)
        })
    })
}
const post = (url, data = {}) => {
    return new Promise((resolve, reject)=>{
       return service({
           url,
           method: 'POST',
           data
       }) .then((res)=>{
           resolve(res.data.data)
       }).catch((err)=>{
           reject(err)
       })
    })
};
export default {
    get,
    post,
    service,
    baseURL
}
